#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright 2013 enen92 
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#######################################################################
import xbmc,xbmcaddon,xbmcgui,xbmcplugin,xbmcvfs,cookielib,urllib,urllib2,os,re,sys,socket
#######################################################################
#######################################################################
addon_id = 'plugin.video.oxe7'
selfAddon = xbmcaddon.Addon(id=addon_id)
addonfolder = selfAddon.getAddonInfo('path')
artfolder = '/resources/img/'
#######################################################################

base_url_subs = 'http://st2.u1.videomega.tv/videos/subs/'
base_url = 'http://oxe7.com/'
base_url_filmes = 'http://oxe7.com/filmes/'
base_url_documentarios = 'http://oxe7.com/documentarios/'
videomega_url = 'http://videomega.tv/'
translate= selfAddon.getLocalizedString

def CATEGORIES():
        addDir('[COLOR blue][B]' + translate(30100) + '[/B][/COLOR]','http://oxe7.com/',4,addonfolder + artfolder + 'starred.png')
        addDir('[COLOR blue][B]' + translate(30101) + '[/B][/COLOR]','http://oxe7.com/page/1/',1,addonfolder + artfolder + 'categories.png')
        addDir('[COLOR blue][B]' + translate(30102) + '[/B][/COLOR]','http://oxe7.com/filmes/dvdrip/page/1',8,addonfolder + artfolder + 'dvdrip.png')
	addDir('[COLOR blue][B]' + translate(30103) + '[/B][/COLOR]','http://oxe7.com/filmes/blu-ray/page/1',8,addonfolder + artfolder + 'bluray.png')
        addDir('[COLOR blue][B]' + translate(30104) + '[/B][/COLOR]','http://oxe7.com/documentarios/page/1/',6,addonfolder + artfolder + 'docs.png')
        addDir('[COLOR blue][B]' + translate(30105) + '[/B][/COLOR]','http://oxe7.com/series/page/1/',10,addonfolder + artfolder + 'tvshows.png')
	addDir('[COLOR blue][B]' + translate(30106) + '[/B][/COLOR]','http://oxe7.com/',22,addonfolder + artfolder + 'search.png')


def TEMA():
	addDir('[COLOR blue][B]' + translate(30107) + '[/B][/COLOR]','http://oxe7.com/action/page/1/',8,addonfolder + artfolder + 'action.png')
	addDir('[COLOR blue][B]' + translate(30108) + '[/B][/COLOR]','http://oxe7.com/adventure/page/1/',8,addonfolder + artfolder + 'adventure.png')
	addDir('[COLOR blue][B]' + translate(30109) + '[/B][/COLOR]','http://oxe7.com/animation/page/1/',8,addonfolder + artfolder + 'animation.png')
	addDir('[COLOR blue][B]' + translate(30110) + '[/B][/COLOR]','http://oxe7.com/comedy/page/1/',8,addonfolder + artfolder + 'comedy.png')
	addDir('[COLOR blue][B]' + translate(30111) + '[/B][/COLOR]','http://oxe7.com/crime/page/1/',8,addonfolder + artfolder + 'crime.png')
        addDir('[COLOR blue][B]' + translate(30112) + '[/B][/COLOR]','http://oxe7.com/drama/page/1/',8,addonfolder + artfolder + 'drama.png')
        addDir('[COLOR blue][B]' + translate(30113) + '[/B][/COLOR]','http://oxe7.com/fantasy/page/1/',8,addonfolder + artfolder + 'fantasy.png')
        addDir('[COLOR blue][B]' + translate(30114) + '[/B][/COLOR]','http://oxe7.com/horror/page/1/',8,addonfolder + artfolder + 'horror.png')
	addDir('[COLOR blue][B]' + translate(30115) + '[/B][/COLOR]','http://oxe7.com/romance/page/1/',8,addonfolder + artfolder + 'love.png')
	addDir('[COLOR blue][B]' + translate(30116) + '[/B][/COLOR]','http://oxe7.com/scy-fi/page/1/',8,addonfolder + artfolder + 'scyfi.png')
	addDir('[COLOR blue][B]' + translate(30117) + '[/B][/COLOR]','http://oxe7.com/thriller/page/1/',8,addonfolder + artfolder + 'thriller.png')
	addDir('[COLOR blue][B]' + translate(30118) + '[/B][/COLOR]','http://oxe7.com/war/page/1/',8,addonfolder + artfolder + 'war.png')
        
def filmes_destaque(url):
	link = abrir_url(url)
	match=re.compile('<li><a href="http://oxe7.com/filmes/(.+?)" title="(.+?)"><span class="movie-name">.+?</span><img src="(.+?)" width=".+?" height=".+?" alt=".+?" title=".+?" /></a></li>').findall(link)
	for urlsbase,titulo,thumbnail in match:
		titulo = dicionario_titulo(titulo)
		addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',base_url_filmes + urlsbase,'5',thumbnail)

def filmes_resolver(url):
	subtitlecheck=selfAddon.getSetting('subtitle-check')
	link = abrir_url(url)
	thumbnail=re.compile('<img src="(.+?)" alt=".+?" class="full-poster" />').findall(link)
	match=re.compile('<iframe src="http://videomega.tv/(.+?)"').findall(link)
	if match == []:
		addDir('[COLOR red][B]' + translate(30120) + '[/B][/COLOR]','http://oxe7.com/','','')
	else:
		for urlsbase in match:
			link = abrir_url(videomega_url + urlsbase)
			match=re.compile('document.write\(unescape\("(.+?)"\)\);').findall(link)
			video_url_escape = urllib.unquote(match[0])
			print video_url_escape
			if subtitlecheck == "true":
				match=re.compile('file: "(.+?)"').findall(video_url_escape)
			else:
				match=re.compile('file: "(.+?)"').findall(video_url_escape)
			tit=re.compile('<div id="title">&nbsp;&nbsp;&nbsp;(.+?)</div>').findall(link)
			addDir_serie('[B]' + tit[0] + '[/B]',videomega_url + urlsbase,13,thumbnail[0])

def series_resolver(url):
	link = abrir_url(url)
	thumbnail=re.compile('<img src="(.+?)" alt=".+?" class="full-poster" />').findall(link)
	match=re.compile('<iframe src="http://videomega.tv/(.+?)"').findall(link)
	for urlsbase in match:
		link = abrir_url(videomega_url + urlsbase)
		match=re.compile('document.write\(unescape\("(.+?)"\)\);').findall(link)
		print match
		if match == []:
			pass
		else:
			tit=re.compile('<div id="title">&nbsp;&nbsp;&nbsp;(.+?)</div>').findall(link)
			video_url_escape = urllib.unquote(match[0])
			match=re.compile('file: "(.+?)"').findall(video_url_escape)
			print match[0]
			addDir_serie('[B]' + tit[0] + '[/B]',videomega_url + urlsbase,13,thumbnail[0])


def video_series_resolver(finalurl,name):
	link = abrir_url(finalurl)
	match=re.compile('document.write\(unescape\("(.+?)"\)\);').findall(link)
	video_url_escape = urllib.unquote(match[0])
	match=re.compile('file: "(.+?)"').findall(video_url_escape)
	thumbnail=re.compile('image:"(.+?)"').findall(video_url_escape)
	subs=re.compile('"file": "(.+?)"').findall(video_url_escape)

	socket.setdefaulttimeout(1000)
	playlist = xbmc.PlayList(1)
	playlist.clear()
	listitem = xbmcgui.ListItem('[B]' + name + '[/B]', iconImage="DefaultVideo.png", thumbnailImage=thumbnail[0])            
	listitem.setInfo("Video", {"Title": name })
	listitem.setProperty('mimetype', 'video/x-msvideo')
	listitem.setProperty('IsPlayable', 'true')
	dialogWait = xbmcgui.DialogProgress()
	dialogWait.create('oxe7.com', 'wait...')
	playlist.add(match[0], listitem)
	dialogWait.close()
	del dialogWait
	player = Player()
	player.play(playlist)
	if selfAddon.getSetting('subtitle-check') == 'true':
		if subs == []:
			pass 
		else:
 			player.setSubtitles(subs[0])
	else:
		xbmc.executebuiltin("XBMC.Notification(oxe7.com,"+ translate(30119) + ",'10000000',"+ addonfolder + artfolder + 'sicon.png'+")")
	while player._playbackLock:
		player._trackPosition()
		xbmc.sleep(250)






def documentarios_list(url,page_logical):
	if page_logical == '0':
		page_num = '1'
		url= base_url_documentarios + '&page=' + page_num
		link = abrir_url(url)
		match=re.compile('<a href="http://oxe7.com/documentarios/(.+?)"><span class="shortlinksfull">.+?\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?<img src=".+?" alt="" class="img" />(.+?)</h2>\n.+?\n.+?\n.+?\n\n.+?\n\n.+?\n.+?\n.+?src="(.+?)"').findall(link)
		for urlsbase,titulo,thumbnail in match:
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',base_url_documentarios + urlsbase,'5',thumbnail)
		match=re.compile('<a href="http://oxe7.com/documentarios/(.+?)"><span class="shortlinksfull">.+?\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?<img src=".+?" alt="" class="img" />(.+?)</h2>\n.+?\n.+?\n.+?\n\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?src="(.+?)".+?\n').findall(link)
		for urlsbase,titulo,thumbnail in match:
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',base_url_documentarios + urlsbase,'5',thumbnail)
		match=re.compile('<a href="http://oxe7.com/filmes/(.+?)"><span class="shortlinksfull">.+?\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?<img src=".+?" alt="" class="img" />(.+?)</h2>\n.+?\n.+?\n.+?\n\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?src="(.+?)".+?\n').findall(link)
		for urlsbase,titulo,thumbnail in match:
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',base_url_filmes + urlsbase,'5',thumbnail)
		pag_num_total=re.compile('.*>(.+?)</a> <a href=".+?">Next &#8594;</a>').findall(link)
		if pag_num_total == []:
			pass
		else:
			page_next_button_documentario(page_num,pag_num_total[0],url)
	else:
		pag_num = re.compile('/page/(.+?)/').findall(url)
		url = base_url_documentarios + 'page/' + pag_num[0] + '/'
		link = abrir_url(url)
		match=re.compile('<a href="http://oxe7.com/documentarios/(.+?)"><span class="shortlinksfull">.+?\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?<img src=".+?" alt="" class="img" />(.+?)</h2>\n.+?\n.+?\n.+?\n\n.+?\n\n.+?\n.+?\n.+?src="(.+?)"').findall(link)
		for urlsbase,titulo,thumbnail in match:
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',base_url_documentarios + urlsbase,'5',thumbnail)
		match=re.compile('<a href="http://oxe7.com/documentarios/(.+?)"><span class="shortlinksfull">.+?\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?<img src=".+?" alt="" class="img" />(.+?)</h2>\n.+?\n.+?\n.+?\n\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?src="(.+?)".+?\n').findall(link)
		for urlsbase,titulo,thumbnail in match:
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',base_url_documentarios + urlsbase,'5',thumbnail)
		match=re.compile('<a href="http://oxe7.com/filmes/(.+?)"><span class="shortlinksfull">.+?\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?<img src=".+?" alt="" class="img" />(.+?)</h2>\n.+?\n.+?\n.+?\n\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?src="(.+?)".+?\n').findall(link)
		for urlsbase,titulo,thumbnail in match:
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',base_url_filmes + urlsbase,'5',thumbnail)
		pag_num_total=re.compile('.*>(.+?)</a> <a href=".+?">Next &#8594;</a>').findall(link)
		if pag_num_total == []:
			pass
		else:
			page_next_button_documentario(pag_num[0],pag_num_total[0],url)

def page_next_button_documentario(page_num,pag_num_total,url):
	page_next =  int(page_num) + 1
	url = base_url_documentarios + 'page/' + str(page_next) + '/'
	addDir('[B]Pag '+ page_num + '/' + pag_num_total + '[/B][B][COLOR blue] | Seguinte >>[/B][/COLOR]',url,7,addonfolder + artfolder + 'next.png')

def filmes_list(url,page_logical,value):
	if page_logical == '0':
		page_num = '1'
		url= base_url + value + '/' + '&page=' + page_num
		link = abrir_url(url)
		match=re.compile('<a href="http://oxe7.com/filmes/(.+?)"><span class="shortlinksfull">.+?\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?<img src=".+?" alt="" class="img" />(.+?)</h2>').findall(link)
		for urlsbase,titulo in match:
			link2 = abrir_url(base_url_filmes + urlsbase)
			thumbnail=re.compile('<img src="(.+?)" alt=".+?" class="full-poster"').findall(link2)
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',base_url_filmes + urlsbase,'5',thumbnail[0])
		pag_num_total=re.compile('.*>(.+?)</a> <a href=".+?">Next &#8594;</a>').findall(link)
		if pag_num_total == []:
			pass
		else:
			page_next_button(page_num,pag_num_total[0],url,value)
	else:
		pag_num = re.compile('/page/(.+?)/').findall(url)
		url = base_url + value + '/page/' + pag_num[0] + '/'
		link = abrir_url(url)
		match=re.compile('<a href="http://oxe7.com/filmes/(.+?)"><span class="shortlinksfull">.+?\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?<img src=".+?" alt="" class="img" />(.+?)</h2>').findall(link)
		for urlsbase,titulo in match:
			link2 = abrir_url(base_url_filmes + urlsbase)
			thumbnail=re.compile('<img src="(.+?)" alt=".+?" class="full-poster"').findall(link2)
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',base_url_filmes + urlsbase,'5',thumbnail[0])
		pag_num_total=re.compile('.*>(.+?)</a> <a href=".+?">Next &#8594;</a>').findall(link)
		if pag_num_total == []:
			pass
		else:
			page_next_button(pag_num[0],pag_num_total[0],url,value)

def page_next_button(page_num,pag_num_total,url,value):
	page_next =  int(page_num) + 1
	url = base_url + value + '/page/' + str(page_next) + '/'
	addDir('[B]Pag '+ page_num + '/' + pag_num_total + '[/B][B][COLOR blue] | ' + translate(30121) + '>>[/B][/COLOR]',url,9,addonfolder + artfolder + 'next.png')

def series_list(url,page_logical,value):
	if page_logical == '0':
		page_num = '1'
		url= base_url + value + '/' + '&page=' + page_num
		link = abrir_url(url)
		match=re.compile('<a href="http://oxe7.com/series/(.+?)"><span class="shortlinksfull">.+?\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?<img src=".+?" alt="" class="img" />(.+?)</h2>').findall(link)
		for urlsbase,titulo in match:
			link2 = abrir_url(base_url_filmes + urlsbase)
			thumbnail=re.compile('<img src="(.+?)" alt=".+?" class="full-poster"').findall(link2)
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',base_url_filmes + urlsbase,'12',thumbnail[0])
		pag_num_total=re.compile('.*>(.+?)</a> <a href=".+?">Next &#8594;</a>').findall(link)
		if pag_num_total == []:
			pass
		else:
			page_next_button_series(page_num,pag_num_total[0],url,value)
	else:
		pag_num = re.compile('/page/(.+?)/').findall(url)
		url = base_url + value + '/page/' + pag_num[0] + '/'
		link = abrir_url(url)
		match=re.compile('<a href="http://oxe7.com/series/(.+?)"><span class="shortlinksfull">.+?\n.+?\n\n.+?\n.+?\n.+?\n.+?\n.+?<img src=".+?" alt="" class="img" />(.+?)</h2>').findall(link)
		for urlsbase,titulo in match:
			link2 = abrir_url(base_url_filmes + urlsbase)
			thumbnail=re.compile('<img src="(.+?)" alt=".+?" class="full-poster"').findall(link2)
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',base_url_filmes + urlsbase,'12',thumbnail[0])
		pag_num_total=re.compile('.*>(.+?)</a> <a href=".+?">Next &#8594;</a>').findall(link)
		if pag_num_total == []:
			pass
		else:
			page_next_button_series(pag_num[0],pag_num_total[0],url,value)

def page_next_button_series(page_num,pag_num_total,url,value):
	page_next =  int(page_num) + 1
	url = base_url + value + '/page/' + str(page_next) + '/'
	addDir('[B]Pag '+ page_num + '/' + pag_num_total + '[/B][B][COLOR blue] | Seguinte >>[/B][/COLOR]',url,11,'')

def pesquisa():
	keyb = xbmc.Keyboard('', 'Escreva o parÃ¢metro de pesquisa')
	keyb.doModal()
        if (keyb.isConfirmed()):
                search = keyb.getText()
                encode=urllib.quote(search)
		pesquisa_resultados(encode)

def pesquisa_resultados(encode):
	urltmp = base_url + 'index.php?do=search&subaction=search&story=' + encode
	programa_pesquisa(urltmp)

def programa_pesquisa(urltmp):
	link = abrir_url(urltmp)
	print link
	match=re.compile('<div class="movieposter" title="Watch Movie (.+?)">\n<a href="(.+?)" ><img src="(.+?)"').findall(link)
	for titulo,url,thumbnail in match:
		link = abrir_url(url)
		match=re.compile('<(.+?)href="http://oxe7.com/filmes/">Filmes</a>').findall(link)
		if match == []:
			pass
		else:
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',url,'5',thumbnail)
		match=re.compile('<(.+?)href="http://oxe7.com/series/">series</a>').findall(link)
		if match == []:
			pass
		else:
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',url,'12',thumbnail)
		match=re.compile('<(.+?)href="http://oxe7.com/documentarios/">Documentarios</a>').findall(link)
		if match == []:
			pass
		else:
			titulo = dicionario_titulo(titulo)	
			addDir('[B][COLOR orange]' + titulo + '[/B][/COLOR]',url,'5',thumbnail)



############################################################################################################################

def dicionario_titulo(titulo):
	titulo = titulo.replace('\xe9', "Ã©");
	titulo = titulo.replace('\xed', "Ã­");
	titulo = titulo.replace('\xf3', "Ã³");
	titulo = titulo.replace('\xe7', "Ã§");
	titulo = titulo.replace('\xe3', "Ã£");
	titulo = titulo.replace('\xe2', "Ã¢");
	titulo = titulo.replace('\xea', "Ãª");
	titulo = titulo.replace('\xe1', "Ã¡");
	titulo = titulo.replace('\xfa', "Ãº");
	titulo = titulo.replace('\xe0', "Ã ");
	return titulo

def abrir_url(url):
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
	return link
            
def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param




def addLink(name,url,iconimage):
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', addonfolder + artfolder + 'fanart.png')
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
	return ok

def addLink_serie(name,url,iconimage):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&name="+urllib.quote_plus(name)+"&iconimage=coiso"
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', addonfolder + artfolder + 'fanart.png')
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz)
	player = Player()
	player.setSubtitles('http://st3.u1.videomega.tv/videos/subs/e63ace48eb8e420f77d80fb76ef0fc41.srt')
	return ok
	

def addDir_serie(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', addonfolder + artfolder + 'fanart.png')
        liz.setInfo( type="Video", infoLabels={ "Title": name })
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok

def addDir(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage=coiso"
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', addonfolder + artfolder + 'fanart.png')
        liz.setInfo( type="Video", infoLabels={ "Title": name })
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok

#Retirado do ADDON do j0anita!
class Player(xbmc.Player):
      def __init__(self):
            xbmc.Player.__init__(self, xbmc.PLAYER_CORE_AUTO)
            self._playbackLock = True
            self._totalTime = 999999
            self._lastPos = 0
            print "Criou o player"

      def onPlayBackStarted(self):
            print "Comecou o player"
            self._totalTime = self.getTotalTime()

      def onPlayBackStopped(self):
            print "Parou o player"
            self._playbackLock = False
            playedTime = int(self._lastPos)
            watched_values = [.7, .8, .9, .95]
            min_watched_percent = watched_values[int(selfAddon.getSetting('watched-percent'))]
            print 'playedTime / totalTime : %s / %s = %s' % (playedTime, self._totalTime, playedTime/self._totalTime)
            if playedTime == 0 and self._totalTime == 999999: raise PlaybackFailed('XBMC falhou a comecar o playback')
            else:
                  print 'Nao atingiu a marca das definicoes. Nao marcou como visto.'

      def onPlayBackEnded(self):              
            self.onPlayBackStopped()
            print 'Chegou ao fim. Playback terminou.'

      def _trackPosition(self):
            try: self._lastPos = self.getTime()
            except: print 'Erro quando estava a tentar definir o tempo de playback'

         
params=get_params()
print params
url=None
name=None
mode=None
iconimage=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass
try:
        mode=int(params["iconimage"])
except:
        pass

print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)

if mode==None or url==None or len(url)<1:
        print ""
        CATEGORIES()
       
elif mode==1:
        print ""+url
        TEMA()
        
elif mode==2:
        print ""+url
        VIDEOLINKS(url,name)

elif mode==4:
        print ""+url
        filmes_destaque(url)

elif mode==5:
        print ""+url
        filmes_resolver(url)

elif mode==6:
        print ""+url
	page_logical='0'
        documentarios_list(url,page_logical)

elif mode==7:
        print ""+url
	page_logical='1'
        documentarios_list(url,page_logical)

elif mode==8:
        print ""+url
	page_logical='0'
	value=re.compile('.*/(.+?)/page/').findall(url)
	print value[0]
        filmes_list(url,page_logical,value[0])

elif mode==9:
        print ""+url
	page_logical='1'
	value=re.compile('.*/(.+?)/page/').findall(url)
        filmes_list(url,page_logical,value[0])

elif mode==10:
        print ""+url
	page_logical='0'
	value=re.compile('.*/(.+?)/page/').findall(url)
	print value[0]
        series_list(url,page_logical,value[0])

elif mode==11:
        print ""+url
	page_logical='1'
	value=re.compile('.*/(.+?)/page/').findall(url)
        series_list(url,page_logical,value[0])

elif mode==12:
        print ""+url
        series_resolver(url)

elif mode==13:
        print ""+url
	video_series_resolver(url,name)

elif mode==22:
        print ""
        pesquisa()



xbmcplugin.endOfDirectory(int(sys.argv[1]))
